<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" v-model="form" ref="crud" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @sort-change="sortChange">
      <!-- @on-load="onLoad"  -->
      <template slot="menuLeft">
        <div>
          <span>视频号生效状态：</span>
          <el-radio-group v-model="wxInfo.isEnable" @change="stautChange" :disabled="!this.wxInfo.uniqId">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </div>
      </template>
      <template slot="menuRight">
        <el-button type="success" size="small" plain v-if="wxInfo.uniqId" @click="apiupdateVideo">同步视频</el-button>
        <el-button type="warning" size="small" plain @click="glsphOpen">{{ wxInfo.uniqId ? '更新' : '关联' }}视频号</el-button>
        <el-button type="danger" size="small" plain  v-if="wxInfo.uniqId" @click="apiunbind">解绑视频号</el-button>
      </template>
      <template slot-scope="scope" slot="cover">
        <el-image :src="scope.row.cover" style="width:40px" @click="imgPreview(scope.row.cover)"></el-image>
      </template>
      <template slot-scope="scope" slot="link">
        <a :href="scope.row.link" target="_blank" style="color: #409EFF;">点击查看</a>
      </template>
      <template slot-scope="scope" slot="isTarget">
        <el-switch v-model="scope.row.isTarget" @change="apiIsTarget(scope.row)" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0">
        </el-switch>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button size="small" type="text" icon="el-icon-connection" @click="glhd(scope.row)">关联活动</el-button>
      </template>
    </avue-crud>

    <!-- 关联活动 -->
    <el-dialog title="关联活动" append-to-body :close-on-click-modal="false" :visible.sync="hdShow">
      <template>
        <videoWxActive ref="videoWxActive" />
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" size="small" @click="hdShow = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="微信【扫一扫】" :before-close="beforeCloseWx" append-to-body :close-on-click-modal="true" width="400px" :visible.sync="glsphShow" v-if="glsphShow">
      <template>
        <div class="flex-c-c">
          <el-image style="width: 300px; height: 300px" :src="wxQrCodeObj.qrCodeLink" :fit="contain"></el-image>

          <div @click="glsphOpen">重新获二维码</div>
        </div>
      </template>
    </el-dialog>

    <el-image-viewer style="z-index: 99999;" v-if="imgShow" :on-close="() => { imgShow = false }" :url-list="imgUrlList"></el-image-viewer>
  </basic-container>
</template>

<script>
import { loginInfo, getQrCode, checkAuth, pageList, updateVideo, delVideo, unbind, changeEnable, setIsTarget } from "@/api/rb-oem/posinfo/videoDrainage";
import videoWxActive from "./video-wx-active";

export default {
  components: { videoWxActive },
  data() {
    return {
      imgShow: false,
      imgUrlList: [],
      hdShow: false,
      rpiNo: "",
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: true,
        selection: false,//列表多选框
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        // menuWidth: 100, //操作栏宽度
        emptyBtnText: '重置',
        // menu: false,
        column: [
          {
            label: "视频号昵称",
            prop: "name",
            type: "input"
          },
          {
            label: "视频标题",
            prop: "title",
            type: "input",
            minWidth: 100
          },
          {
            label: '视频封面',
            prop: 'cover',
            type: "input",
            width: 80
          },
          {
            label: "视频链接",
            prop: "link",
            type: "input",
            minWidth: 100
          },
          {
            label: "是否跳转",
            prop: "isTarget",
            type: "select",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
          },
          {
            label: "点赞量",
            prop: "favCount",
            type: "input",
            minWidth: 100
          },
          {
            label: "评论量",
            prop: "commentCount",
            type: "input",
            minWidth: 100
          },
          {
            label: "转发量",
            prop: "forwardCount",
            type: "input",
            minWidth: 100
          },
          {
            label: "喜欢量",
            prop: "likeCount",
            type: "input",
            minWidth: 100
          },
          {
            label: "播放量",
            prop: "readCount",
            type: "input",
            minWidth: 100
          }
        ]
      },
      wxInfo: {
        headImgUrl: "",//用户头像
        isEnable: 0,//
        nickName: "",//用户昵称
        rpiNo: "",//商户号
        uniqId: ""//用户id
      },
      glsphShow: false,//关联视频号弹框
      wxQrCodeObj: {
        qrCodeLink: '',//二维码
        token: ''
      },
      qrCodeTimer: null,//定时器
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    base64() {
      return (val) => {
        if (val) {
          if (val.indexOf('data:image/png;base64,') == -1) {
            return ('data:image/png;base64,' + val);
          } else {
            return val;
          }
        } else {
          return ''
        }
      };
    }
  },
  created() {
    this.rpiNo = this.$route.query.rpiNo;
    this.apiloginInfo(false)
  },
  methods: {
    apiIsTarget(item) {
      let param = {
        changeType: item.isTarget,
        exportId: item.exportId
      }
      setIsTarget(param).then(({ data }) => {
        if (data.code === 200) {
          this.$message.success(data.msg);
        } else {
          this.$message.error(data.msg);
          if (item.isTarget) {
            item.isTarget = 0
          } else {
            item.isTarget = 1
          }
        }
      },(error) =>{
        if (item.isTarget) {
            item.isTarget = 0
          } else {
            item.isTarget = 1
          }
      })
    },
    // 解绑视频号
    apiunbind() {
      let _this = this;
      this.$confirm("确定将选择解绑活动?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return unbind(this.rpiNo).then(() => {
            _this.wxInfo = {
              headImgUrl: "",//用户头像
              isEnable: 0,//
              nickName: "",//用户昵称
              rpiNo: "",//商户号
              uniqId: ""//用户id
            }
          });
        })
        .then(() => {
          _this.onLoad(this.page);
          _this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    /* 预览图片 */
    imgPreview(url) {
      this.imgUrlList[0] = url;
      this.imgShow = true;
    },
    /**
     * 获取微信登录信息
     * @desc isTB: true 同步更新视频 | false 不同步更新视频
    */
    apiloginInfo(isTB) {
      loginInfo(this.rpiNo).then(({ data }) => {
        this.wxInfo = data.data
        if (this.wxInfo.uniqId) {
          if (isTB){
            this.apiupdateVideo()
          } else {
            this.page.currentPage = 1;
            this.onLoad(this.page);
          }
        }
      });
    },
    /**
     * 更新视频 
     * @desc 1.wxInfo.uniqId 有值调用列表不同步视频  2.扫码后同步视频
    */
    apiupdateVideo() {
      updateVideo(this.rpiNo).then(({ data }) => {
        if (data.code === 200) {
          this.$message.success(data.msg);
          this.page.currentPage = 1;
          this.onLoad(this.page);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 打开关联视频号弹框
    glsphOpen() {
      clearInterval(this.qrCodeTimer)
      this.wxQrCodeObj = {
        qrCodeLink: '',//二维码
        token: ''
      }
      getQrCode(this.rpiNo).then(({ data }) => {
        this.wxQrCodeObj = data.data
        this.glsphShow = true;
        this.setQrCodeTimer()
      });
    },
    // 设置定时器
    setQrCodeTimer() {
      this.qrCodeTimer = setInterval(() => {
        // let formData = new FormData();
        // formData.append('rpiNo',this.rpiNo)
        // formData.append('token',this.wxQrCodeObj.token)
        let formData = {
          rpiNo: this.rpiNo,
          token: this.wxQrCodeObj.token
        }
        checkAuth(formData).then(({ data }) => {
          let res = data.data
          if (data.code == 200) {
            // loginCode	登陆状态码0成功 -1失败 100需持续查询
            if (res.loginCode == '0') {
              clearInterval(this.qrCodeTimer)
              this.glsphShow = false;

              this.apiloginInfo(true)
            } else if (res.loginCode == '-1') {
              clearInterval(this.qrCodeTimer)
              this.glsphShow = false;
            }
          } else {
            clearInterval(this.qrCodeTimer)
            this.glsphShow = false;
          }
        }, (error) => {
          clearInterval(this.qrCodeTimer)
          this.glsphShow = false;
        });
      }, 2000)
    },
    beforeCloseWx(done) {
      //清除定时器
      clearInterval(this.qrCodeTimer)
      done()
    },
    /* 关联活动 */
    glhd(row) {
      this.hdShow = true;
      this.$nextTick(() => {
        this.$refs.videoWxActive.hdOpen(row)
      })
    },
    /* 列表删除 */
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delVideo(row.exportId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    /* 视频号生效状态 */
    stautChange(isEnable) {
      let param = {
        rpiNo: this.rpiNo,
        isEnable
      }
      changeEnable(param).then(({ data }) => {
        if (data.code === 200) {
          this.$message.success(data.msg);
        } else {
          this.$message.error(data.msg);
          isEnable === 1 ? this.wxInfo.isEnable = 0 : this.wxInfo.isEnable = 1
        }
      }, (error) => {
        isEnable === 1 ? this.wxInfo.isEnable = 0 : this.wxInfo.isEnable = 1
      });
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      let paramObj = Object.assign(params, this.query);
      paramObj.rpiNo = this.rpiNo
      // 同步视频 列表
      pageList(
        page.currentPage,
        page.pageSize,
        paramObj
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/ .avue-crud__left {
  display: flex;
  justify-content: center;
  align-items: center;
}

/deep/ .el-dialog__body {
  padding: 0 20px 30px;
}

.flex-c-c {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>